import axios from 'axios';

/**
 * 前端日志工具类
 * 支持错误上报、本地存储、分级日志
 */
class FrontendLogger {
  constructor() {
    this.enabled = process.env.NODE_ENV !== 'production'
    this.levels = ['error', 'warn', 'info', 'debug']
    this.maxLocalLogs = 100
  }

  /**
   * 错误级别日志
   */
  error(message, data = {}) {
    this.log('error', message, data);
    // 生产环境自动上报错误
    if (process.env.NODE_ENV === 'production') {
      this.reportToServer('error', message, data)
    }
  }

  /**
   * 警告级别日志
   */
  warn(message, data = {}) {
    this.log('warn', message, data)
  }

  /**
   * 信息级别日志
   */
  info(message, data = {}) {
    this.log('info', message, data)
  }

  /**
   * 调试级别日志（仅开发环境）
   */
  debug(message, data = {}) {
    if (this.enabled) {
      this.log('debug', message, data)
    }
  }

  /**
   * 统一日志处理方法
   */
  log(level, message, data) {
    const timestamp = new Date().toISOString();
    const logEntry = {
      timestamp,
      level,
      message,
      data,
      page: window.location.href,
      userAgent: navigator.userAgent,
      userId: this.getUserId()
    };

    // 控制台输出（带颜色）
    this.consoleOutput(level, timestamp, message, data);

    // 开发环境保存到本地存储
    if (this.enabled) {
      this.saveToLocalStorage(logEntry);
    }
  }

  /**
   * 控制台输出
   */
  consoleOutput(level, timestamp, message, data) {
    const styles = {
      error: 'color: red; font-weight: bold;',
      warn: 'color: orange; font-weight: bold;',
      info: 'color: blue;',
      debug: 'color: gray;'
    };

    const consoleMessage = `%c[${timestamp}] ${level.toUpperCase()}: ${message}`;
    
    if (data && Object.keys(data).length > 0) {
      console.groupCollapsed(consoleMessage, styles[level]);
      console.log('详情:', data);
      console.groupEnd();
    } else {
      console.log(consoleMessage, styles[level]);
    }
  }

  /**
   * 上报日志到服务端
   */
  async reportToServer(level, message, data) {
    try {
      await axios.post('/api/log/client', {
        level,
        message,
        data: this.sanitizeData(data),
        timestamp: new Date().toISOString(),
        page: window.location.href,
        userId: this.getUserId(),
        userAgent: navigator.userAgent
      });
    } catch (error) {
      // 静默失败，避免循环错误
      console.error('日志上报失败:', error);
    }
  }

  /**
   * 数据脱敏处理
   */
  sanitizeData(data) {
    if (!data || typeof data !== 'object') return data;
    
    const sensitiveFields = ['password', 'token', 'authorization', 'cardNo', 'idCard'];
    const sanitized = { ...data };
    
    sensitiveFields.forEach(field => {
      if (sanitized[field]) {
        sanitized[field] = '***';
      }
    });
    
    return sanitized;
  }

  /**
   * 保存到本地存储
   */
  saveToLocalStorage(logEntry) {
    try {
      const logs = JSON.parse(localStorage.getItem('frontend_logs') || '[]');
      logs.push(logEntry);
      
      // 限制日志数量
      if (logs.length > this.maxLocalLogs) {
        logs.splice(0, logs.length - this.maxLocalLogs);
      }
      
      localStorage.setItem('frontend_logs', JSON.stringify(logs));
    } catch (e) {
      // 忽略存储错误
    }
  }

  /**
   * 获取当前用户ID
   */
  getUserId() {
    try {
      const userInfo = localStorage.getItem('user_info');
      return userInfo ? JSON.parse(userInfo).id : 'anonymous';
    } catch {
      return 'anonymous';
    }
  }

  /**
   * 获取本地存储的日志
   */
  getLocalLogs() {
    try {
      return JSON.parse(localStorage.getItem('frontend_logs') || '[]');
    } catch (e) {
      return [];
    }
  }

  /**
   * 清空本地日志
   */
  clearLocalLogs() {
    try {
      localStorage.removeItem('frontend_logs');
    } catch (e) {
      // 忽略错误
    }
  }

  /**
   * 导出日志（用于问题反馈）
   */
  exportLogs() {
    const logs = this.getLocalLogs();
    const logText = logs.map(log => 
      `[${log.timestamp}] ${log.level.toUpperCase()}: ${log.message} ${JSON.stringify(log.data)}`
    ).join('\n');
    
    const blob = new Blob([logText], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `frontend-logs-${new Date().toISOString().split('T')[0]}.txt`;
    a.click();
    URL.revokeObjectURL(url);
  }
}

// 创建单例实例
const logger = new FrontendLogger();

// 全局错误监听
window.addEventListener('error', (event) => {
  logger.error('全局JavaScript错误', {
    message: event.message,
    filename: event.filename,
    lineno: event.lineno,
    colno: event.colno,
    error: event.error?.stack
  });
});

window.addEventListener('unhandledrejection', (event) => {
  logger.error('未处理的Promise拒绝', {
    reason: event.reason?.message || event.reason
  });
});

export default logger;